package com.jiubanqingchen.wish.framework.support;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricCrypto;
import cn.hutool.crypto.asymmetric.KeyType;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jiubanqingchen.wish.framework.exception.WishException;
import com.jiubanqingchen.wish.framework.exception.WishExceptionKey;

/**
 * 加密支持类
 *
 * @author light_dust
 * @since 2020/9/24 17:33
 */
public class EncryptionSupport {

    private static final EncryptionSupport me = new EncryptionSupport();

    private AsymmetricCrypto asymmetricCrypto;//rsa加密

    public static EncryptionSupport me() {
        return me;
    }

    /**
     * 加密密码
     *
     * @param password 密码
     * @since 2020/9/24 17:44
     **/
    public String encrypPassword(String password) throws WishException {
        return encryp(md5Password(password));
    }

    /**
     * 明文加密成MD5
     *
     * @param password 加密密码
     * @since 2020/9/25 10:39
     **/
    public String md5Password(String password) throws WishException {
        if (StrKit.isBlank(password)) throw new WishException(WishExceptionKey.USER_ENCRYP_PASSWORD_IS_NOT_NULL);
        String slat = "jiubanqingchen@outlook.com&&2020-2021";//加个盐
        return SecureUtil.md5(password + slat);
    }

    /**
     * 判断明文密码是否与密文密码相等
     *
     * @param password       明文密码
     * @param encrypPassword 密文密码
     * @since 2020/9/25 10:36
     **/
    public boolean decrypPassword(String password, String encrypPassword) throws WishException {
        return md5Password(password).equals(decryp(encrypPassword));
    }

    /**
     * 加密字符串
     *
     * @param content 被加密内容
     * @since 2020/9/25 10:34
     **/
    public String encryp(String content) {
        return getAsymmetricCrypto().encryptBase64(content, KeyType.PublicKey);
    }

    /**
     * 解密字符串
     *
     * @param encrypStr 被加密过的字符串
     * @since 2020/9/25 10:35
     **/
    public String decryp(String encrypStr) {
        return getAsymmetricCrypto().decryptStr(encrypStr, KeyType.PrivateKey);
    }

    public AsymmetricCrypto getAsymmetricCrypto() {
        if (asymmetricCrypto == null) {
            Prop prop = PropKit.use("rsa.properties");
            asymmetricCrypto = new AsymmetricCrypto("RSA", prop.get("privateKey"), prop.get("publicKey"));
        }
        return asymmetricCrypto;
    }
}
